package me.zhengjie.minio;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriUtils;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class MinioUtils {

    public static Map<String, String> upload(MultipartFile multipartFile) throws Exception  {
    //    MinioClient minioClient = new MinioClient(WeiXinConfig.endPoint, WeiXinConfig.accessKey, WeiXinConfig.secretKey);
        Map<String, String> map = new HashMap<>();
        MinioClient minioClient = MinioClient.builder()
                .endpoint(MinioConfig.endPoint)
                .credentials(MinioConfig.accessKey, MinioConfig.secretKey)
                .build();
        log.info("getOriginalFilename : {}", multipartFile.getOriginalFilename());
        String suffix = getSuffix(multipartFile.getOriginalFilename());


        //        创建新文件名 系统时间+4个随机字符   防止出现重名覆盖现象
//        创建的文件名就是 img 的url

        String datetime = DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN);
        String date = datetime.substring(0, 8);
        String time = datetime.substring(8);
        String bucket = MinioConfig.bucket+"."+date;

                StringBuilder newName = new StringBuilder();
        newName.append(RandomStringUtils.random(4, true, true))
                .append(date)
                .append(RandomStringUtils.random(4, true, true))
                .append(time)
                .append(".")
                .append(suffix);

        // bucket 不存在，创建
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build())) {
        //    minioClient.makeBucket(bucket);
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
            String config = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\"],\"Effect\":\"Allow\",\"Principal\":\"*\",\"Resource\":\"arn:aws:s3:::"+bucket+"\"},{\"Action\":\"s3:GetObject\",\"Effect\":\"Allow\",\"Principal\":\"*\",\"Resource\":\"arn:aws:s3:::"+bucket+"/*\"}]}";
        //    minioClient.setBucketPolicy(bucket, PolicyType.READ_ONLY);
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucket).config(config).build());
        }

//        InputStream inputStream = multipartFile.getInputStream();

        // PutObjectOptions，上传配置(文件大小，内存中文件分片大小)
/*
        PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
        // 文件的ContentType
        putObjectOptions.setContentType(multipartFile.getContentType());
        minioClient.putObject(bucket, newName.toString(), inputStream, putObjectOptions);
*/

        PutObjectArgs objectArgs = PutObjectArgs.builder()
                .contentType(multipartFile.getContentType())
                .stream(multipartFile.getInputStream(), multipartFile.getSize(), 0)
                .bucket(bucket)
                .object(newName.toString())
                .build();
        minioClient.putObject(objectArgs);



        // 返回访问路径
        String url = MinioConfig.endPoint3 + "/" + bucket + "/" + UriUtils.encode(newName.toString(), StandardCharsets.UTF_8);
        String url2 = MinioConfig.endPoint + "/" + bucket + "/" + UriUtils.encode(newName.toString(), StandardCharsets.UTF_8);
        String url3 = MinioConfig.endPoint2 + "/" + bucket + "/" + UriUtils.encode(newName.toString(), StandardCharsets.UTF_8);
        map.put("url", url);
        map.put("url2", url2);
        map.put("url3", url3);
        map.put("filename", newName.toString());
        return map;
    }


    public static Map<String, String> uploadNurseList(MultipartFile multipartFile) throws Exception  {
        Map<String, String> map = new HashMap<>();
        MinioClient minioClient = MinioClient.builder()
                .endpoint(MinioConfig.endPoint)
                .credentials(MinioConfig.accessKey, MinioConfig.secretKey)
                .build();
        log.info("getOriginalFilename : {}", multipartFile.getOriginalFilename());
        String suffix = getSuffix(multipartFile.getOriginalFilename());


        //        创建新文件名 系统时间+4个随机字符   防止出现重名覆盖现象
//        创建的文件名就是 img 的url

        String datetime = DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN);
        String date = datetime.substring(0, 8);
        String time = datetime.substring(8);
        String bucket = "nurselist";

        StringBuilder newName = new StringBuilder();
        newName.append(RandomStringUtils.random(4, true, true))
                .append(date)
                .append(RandomStringUtils.random(4, true, true))
                .append(time)
                .append(".")
                .append(suffix);

        PutObjectArgs objectArgs = PutObjectArgs.builder()
                .contentType(multipartFile.getContentType())
                .stream(multipartFile.getInputStream(), multipartFile.getSize(), 0)
                .bucket(bucket)
                .object(newName.toString())
                .build();
        minioClient.putObject(objectArgs);

        // 返回访问路径
        String url = MinioConfig.endPoint3 + "/" + bucket + "/" + UriUtils.encode(newName.toString(), StandardCharsets.UTF_8);
        String url2 = MinioConfig.endPoint + "/" + bucket + "/" + UriUtils.encode(newName.toString(), StandardCharsets.UTF_8);
        String url3 = MinioConfig.endPoint2 + "/" + bucket + "/" + UriUtils.encode(newName.toString(), StandardCharsets.UTF_8);
        map.put("url", url);
        map.put("url2", url2);
        map.put("url3", url3);
        map.put("filename", newName.toString());
        return map;
    }


    public static Map<String, String> uploadNurseFace(MultipartFile multipartFile) throws Exception  {
        Map<String, String> map = new HashMap<>();
        MinioClient minioClient = MinioClient.builder()
                .endpoint(MinioConfig.endPoint)
                .credentials(MinioConfig.accessKey, MinioConfig.secretKey)
                .build();
        log.info("getOriginalFilename : {}", multipartFile.getOriginalFilename());
        String suffix = getSuffix(multipartFile.getOriginalFilename());


        //        创建新文件名 系统时间+4个随机字符   防止出现重名覆盖现象
//        创建的文件名就是 img 的url

        String datetime = DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_PATTERN);
        String date = datetime.substring(0, 8);
        String time = datetime.substring(8);
        String bucket = MinioConfig.bucketFace+"."+date;

        StringBuilder newName = new StringBuilder();
        newName.append(RandomStringUtils.random(4, true, true))
                .append(date)
                .append(RandomStringUtils.random(4, true, true))
                .append(time)
                .append(".")
                .append(suffix);

        PutObjectArgs objectArgs = PutObjectArgs.builder()
                .contentType(multipartFile.getContentType())
                .stream(multipartFile.getInputStream(), multipartFile.getSize(), 0)
                .bucket(bucket)
                .object(newName.toString())
                .build();
        minioClient.putObject(objectArgs);

        // 返回访问路径
        String url = MinioConfig.endPoint3 + "/" + bucket + "/" + UriUtils.encode(newName.toString(), StandardCharsets.UTF_8);
        String url2 = MinioConfig.endPoint + "/" + bucket + "/" + UriUtils.encode(newName.toString(), StandardCharsets.UTF_8);
        String url3 = MinioConfig.endPoint2 + "/" + bucket + "/" + UriUtils.encode(newName.toString(), StandardCharsets.UTF_8);
        map.put("url", url);
        map.put("url2", url2);
        map.put("url3", url3);
        map.put("filename", newName.toString());
        return map;
    }

    /**
     * 获取文件后缀
     * @param fileName
     * @return
     */
    protected static String getSuffix(String fileName) {
        int index = fileName.lastIndexOf(".");
        if (index != -1) {
            String suffix = fileName.substring(index + 1);
            if (!suffix.isEmpty()) {
                return suffix;
            }
        }
        throw new IllegalArgumentException("非法文件名称："  + fileName);
    }

}
